package org.dev.pf.iof.systemmanage.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.dev.pf.iof.base.constants.IofConstants;
import org.dev.pf.iof.systemmanage.model.IofMenuinfo;

import com.jgeppert.struts2.jquery.tree.result.TreeNode;

public class TreeUtil {

	public static  Map<Long, List<IofMenuinfo>> buildingMenuMap(
			List<IofMenuinfo> menuList) throws Exception {
		Map<Long, List<IofMenuinfo>> results = new HashMap<Long, List<IofMenuinfo>>();
		for (IofMenuinfo menu : menuList) {
			Long iparentid = IofConstants.TOP_MENU_IID_LONG;
			if (menu.getIparentid() != null) {
				iparentid = menu.getIparentid();
			}
			List<IofMenuinfo> objList = results.get(iparentid);
			if (objList == null) {
				objList = new ArrayList<IofMenuinfo>();
			}
			objList.add(menu);
			results.put(iparentid, objList);
		}
		return results;
	}

	public static List<TreeNode> buildingForList(Long iparentid,
			Map<Long, List<IofMenuinfo>> menuMap) throws Exception {
		List<TreeNode> results = new ArrayList<TreeNode>();
		List<IofMenuinfo> menus = menuMap.get(iparentid);
		if (CollectionUtils.isNotEmpty(menus)) {
			for (IofMenuinfo menu : menus) {
				TreeNode node = new TreeNode();
				if(StringUtils.isNotBlank(menu.getSaction())){
					node.setId(menu.getIid()+"@"+menu.getSaction());
					node.getAttr().put("action", menu.getSaction());
				}else{
					node.setId(menu.getIid().toString());
				}
				
				node.setTitle(menu.getSmenuname());
				List<TreeNode> chilidrens=buildingForList(menu.getIid(), menuMap);
				if(CollectionUtils.isEmpty(chilidrens)){
					node.setState(TreeNode.NODE_STATE_LEAF);
				}
				
				node.setChildren(chilidrens);
				results.add(node);
			}
		}
		return results;

	}

	public static List<TreeNode> buildingMenuList(List<IofMenuinfo> menuList)
			throws Exception {
		List<TreeNode> results = new ArrayList<TreeNode>();
		Map<Long, List<IofMenuinfo>> maps = buildingMenuMap(menuList);
		results.addAll(buildingForList(IofConstants.TOP_MENU_IID_LONG, maps));
		return results;
	}

}
